﻿// ====================================
// Created By Angie.D 2010.6
// ====================================

using System;
using System.Collections.Generic;
using System.Text;

using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WOWMultiPlay
{
    [XmlRootAttribute("mpHotkey", IsNullable = false)]
    public class mpHotkey
    {
        public int Hotkey;
        public int Mods;

        [XmlIgnore]
        public IntPtr Handle;
        [XmlIgnore]
        public short HotkeyID;
        [XmlIgnore]
        public Button WinFormButton;

        public delegate void ReceivedHotkey(object sender, Button btn);
        public event ReceivedHotkey OnReceivedHotkey;

        public mpHotkey() { }

        public mpHotkey(int hotkey, int mods)
        {
            this.Hotkey = hotkey;
            this.Mods = mods;
        }

        public mpHotkey(int hotkey, int mods, IntPtr handle)
        {
            this.Hotkey = hotkey;
            this.Mods = mods;
            this.Handle = handle;
        }

        public void RegisterGlobalHotKey()
        {
            UnregisterGlobalHotKey();

            try
            {
                string atomName = Guid.NewGuid().ToString();
                HotkeyID = WindowsAPI.GlobalAddAtom(atomName);

                if (HotkeyID == 0)
                {
                    throw new Exception("Can't generate unique hotkey ID.");
                }

                if (!WindowsAPI.RegisterHotKey(this.Handle, HotkeyID, this.Mods, (int)this.Hotkey))
                {
                    throw new Exception(string.Format("Can't register hotkey '{0}+{1}'.", Common.GetMODName(this.Mods), Common.GetVKName(this.Hotkey)));
                }
            }
            catch (Exception e)
            {
                UnregisterGlobalHotKey();
                throw e;
            }
        }

        public void UnregisterGlobalHotKey()
        {
            if (this.HotkeyID != 0)
            {
                WindowsAPI.UnregisterHotKey(this.Handle, HotkeyID);
                WindowsAPI.GlobalDeleteAtom(HotkeyID);
                HotkeyID = 0;
            }
        }

        public void ProcessHotkey(Message msg)
        {
            if (msg.Msg == WindowsAPI.WM.WM_HOTKEY)
            {
                if ((short)msg.WParam == this.HotkeyID)
                {
                    OnReceivedHotkey(this, WinFormButton);
                }
            }
        }
    }
}